package sanshui.system.trade.controller;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;
import sanshui.system.trade.common.CommonResponse;
import sanshui.system.trade.common.GlobalContain;
import sanshui.system.trade.common.TradeType;
import sanshui.system.trade.factory.data.DataMarketType;
import sanshui.system.trade.factory.trade.worker.AbstractTradeWorker;
import sanshui.system.trade.model.PositionAccModel;
import sanshui.system.trade.model.TradeReportModel;
import sanshui.system.trade.model.TradeWorkerModel;
import sanshui.system.trade.pojo.ao.FrontOpWorkerAo;
import sanshui.system.trade.service.ITradeHisOpPosService;
import sanshui.system.trade.service.IWorkerService;
import sanshui.system.trade.util.CommonTimeUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ApiOperation("Worker接口")
@Slf4j
@RestController
@RequestMapping("/worker")
public class TradeWorkerController {

    @Resource
    IWorkerService workerService;
    @Resource
    ITradeHisOpPosService tradeHisOpPosService;

    @PostMapping("/query/list")
    @ApiOperation(value = "worker带条件查询")
    public List<TradeWorkerModel> queryList(@RequestBody TradeWorkerModel workerModel) {
        log.info("查询workerModel:{}", workerModel);
        return workerService.selectWorkerList(workerModel);
    }

    @PostMapping("/add/back")
    @ApiOperation(value = "新增回测交易")
    public Boolean addBackTrade(@RequestBody TradeWorkerModel workerModel) {
        log.info("查询workerModel:{}", workerModel);
        return workerService.buildBackTradeWorker(workerModel);
    }

    @GetMapping("/report/{workerId}")
    @ApiOperation(value = "worker交易结果")
    public CommonResponse<TradeReportModel> report(@PathVariable("workerId") Long workerId) {
        log.info("查询worker:{}", workerId);
        return CommonResponse.ok(workerService.selectWorkerReportById(workerId));
    }

    @GetMapping("/query/all")
    public CommonResponse<List<TradeWorkerModel>> queryAll() {
        List<TradeWorkerModel> models = workerService.selectWorkers(null);
        log.info("查询所有结果:{}", models.size());
        return CommonResponse.ok(models);
    }

    @GetMapping("/query/{workerId}")
    @ApiOperation(value = "查询worker")
    public CommonResponse<TradeWorkerModel> queryOne(@PathVariable("workerId") Long workerId) {
        log.info("查询worker:{}", workerId);
        return CommonResponse.ok(workerService.selectWorkerModelById(workerId));
    }

    @GetMapping("/query/{accId}/{workerId}/{datetime}")
    @ApiOperation(value = "查询账户下的worker的持有仓位")
    public CommonResponse<Map<String, PositionAccModel>> queryHoldPosInWorker(@PathVariable("accId") Long accId,
                                                                              @PathVariable("workerId") Long workerId,
                                                                              @PathVariable("datetime") String datetime) {
        log.info("查询worker:{}, accId:{}", workerId, accId);
        if (Strings.isEmpty(datetime)) {
            datetime = CommonTimeUtil.getNowTime16();
        }
        if (null == workerId || 0 == workerId) {
            tradeHisOpPosService.selectAccHoldPosModels(accId, datetime);
        }

        if (null == accId || 0 == accId) {
            tradeHisOpPosService.selectWorkerHoldPosModels(workerId, datetime);
        }
        return CommonResponse.ok(tradeHisOpPosService.selectAccWorkerHoldPosModels(accId, workerId, datetime, DataMarketType.T1));
    }

    @PostMapping("/opWorker")
    @ApiOperation(value = "操作workerId")
    public Boolean opWorker(@RequestBody FrontOpWorkerAo opWorkerAo) {
        List<String> workerIds = opWorkerAo.getWorkerId();
        for (String workerId : workerIds) {
            String opType = opWorkerAo.getOpType();
            log.info("workerId:{}, op:{}", workerId, opType);
            if (TradeType.WorkerOpStatus.STOP.name().equalsIgnoreCase(opType)) {
                AbstractTradeWorker runWorker = GlobalContain.tradeSystemExecutor.getWorkerByWorkerId(workerId);
                if (runWorker != null){
                    log.info("停止了该任务");
                    runWorker.stop();
                } else {
                    workerService.updateWorkerStatusByWorkerId(Long.parseLong(workerId), TradeType.WorkerStatus.END, TradeType.WorkerStatus.IN);
                }
            }
            if (TradeType.WorkerOpStatus.START.name().equalsIgnoreCase(opType)) {
                log.info("该任务加入队列");
                workerId = workerService.runRtWorker(workerId);
            }
        }
        return true;
    }
}